package com.frozenlab.android.weather.helper;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import android.util.Log;

import com.frozenlab.android.weather.vo.LocationVO;

public class YahooPlaceFinderHelper {

	private static final String TAG = "YahooPlaceFinderHelper";
	private static final String TAG_WOEID = "woeid";
	private static final String TAG_LATITUDE = "latitude";
	private static final String TAG_LONGITUDE = "longitude";
	private static final String TAG_NEIGHBORHOOD = "neighborhood";
	
	public static String createUrl(String latitude, String longitude) {
		//contruct url to use yahoo place finder web services to get location detail eg: WOEID
		//example: http://where.yahooapis.com/geocode?q=3.156912,101.714677&gflags=R&appid=[yahoo_app_id]
		String strUrl = YahooDataConstant.YAHOO_PLACE_FINDER_BASE_URI;
		strUrl = strUrl + "q=" + latitude +","+ longitude + "&gflags=R&appid=" + YahooDataConstant.YAHOO_APP_ID;
			
		return strUrl;
	}	
	
	public static LocationVO parserYahooPlaceFinderInfo(Document doc){
		if (doc == null){
			Log.e(TAG,"Document is NULL");
			return null;
		}
		
		LocationVO locationVO = new LocationVO();
		
		String woeid = null;
		String latitude = null;
		String longitude = null;
		String neighborhood = null;
		
		try {
			Element root = doc.getDocumentElement();
			root.normalize();
	
			woeid = root.getElementsByTagName(TAG_WOEID).item(0).getFirstChild().getNodeValue();
			latitude = root.getElementsByTagName(TAG_LATITUDE).item(0).getFirstChild().getNodeValue();
			longitude = root.getElementsByTagName(TAG_LONGITUDE).item(0).getFirstChild().getNodeValue();
			neighborhood = root.getElementsByTagName(TAG_NEIGHBORHOOD).item(0).getFirstChild().getNodeValue();
			
			locationVO.setWoeid(woeid);
			locationVO.setLatitude(latitude);
			locationVO.setLongitude(longitude);
			locationVO.setNeighbourhood(neighborhood);
			
		} catch (Exception e){
			Log.e(TAG,e.toString());
			return null;
		}

		return locationVO;
	}


}
